﻿using MobileClient.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using MobileClient.DataModel;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using Windows.UI.Popups;
using Windows.Storage.Streams;
using System.Text;
using System.Threading.Tasks;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace MobileClient.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class NewAccount : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        private System.Net.Http.HttpClient httpClient;

        public NewAccount()
        {
            this.InitializeComponent();

            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += this.NavigationHelper_LoadState;
            this.navigationHelper.SaveState += this.NavigationHelper_SaveState;

            //use to connect web API
            httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("http://localhost:60423/");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            // Limit the max buffer size for the response so we don't get overwhelmed
            httpClient.MaxResponseContentBufferSize = 266000;




        }

        /// <summary>
        /// Gets the <see cref="NavigationHelper"/> associated with this <see cref="Page"/>.
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        /// <summary>
        /// Gets the view model for this <see cref="Page"/>.
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
        /// <param name="e">Event data that provides an empty dictionary to be populated with
        /// serializable state.</param>
        private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }

        #region NavigationHelper registration

        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
        }

        #endregion


        private async void create_Click(object sender, RoutedEventArgs e)
        {
            User user = new User();
            string emailPattern = @"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
            string namePattern = @"^[A-Z]'?[- a-zA-Z]+$";
            string zipPattern = @"^[0-9]{4}$";
            string phonePattern = @"^[0-9]{8}$";
            Regex emailRgx = new Regex(emailPattern, RegexOptions.IgnoreCase);
            Regex nameRgx = new Regex(namePattern, RegexOptions.IgnoreCase);
            Regex zipRgx = new Regex(zipPattern, RegexOptions.IgnoreCase);
            Regex phoneRgx = new Regex(phonePattern, RegexOptions.IgnoreCase);
            MatchCollection emailMatches = emailRgx.Matches(emailTextBox.Text);
            MatchCollection nameMatches = nameRgx.Matches(nameTextBox.Text);
            MatchCollection zipMatches = zipRgx.Matches(zipCodeTextBox.Text);
            MatchCollection cityMatches = nameRgx.Matches(cityTextBox.Text);
            MatchCollection phoneMatches = phoneRgx.Matches(phoneTextBox.Text);

            if (emailMatches.Count < 1)
            {
                emailTextBox.Header = "Email -> Ugyldig Email";
            }
            else if (passwordPassBox.Password == "")
            {
                passwordPassBox.Header = "Password -> Skriv et password";
                emailTextBox.Header = "Email";
            }
            else if (passwordPassBox.Password != confirmPasswordPassBox.Password)
            {
                confirmPasswordPassBox.Header = "Bekræft password -> Password er ikke ens";
                passwordPassBox.Header = "Password";
            }
            else if (nameMatches.Count < 1)
            {
                nameTextBox.Header = "Navn -> Navn må ikke indeholde tal";
                confirmPasswordPassBox.Header = "Bekræft password";
            }
            else if (addressTextBox.Text == "")
            {
                addressTextBox.Header = "Adresse -> Skriv en adresse";
                nameTextBox.Header = "Navn";
            }
            else if (zipMatches.Count < 1)
            {
                zipCodeTextBox.Header = "Postnummer -> Ugyldig postnummer";
                addressTextBox.Header = "Adresse";
            }
            else if (cityMatches.Count < 1)
            {
                cityTextBox.Header = "BY -> By må ikke indeholde tal";
                zipCodeTextBox.Header = "Postnummer";
            }
            else if (phoneMatches.Count < 1)
            {
                phoneTextBox.Header = "Telefonnummer -> Telefonnummer skal være 8 tal";
                cityTextBox.Header = "By";
            }
            else
            {
                // Assign variables from textboxes to user object
                user.User_City = cityTextBox.Text;
                user.User_Address = addressTextBox.Text;
                user.User_ZipCode = Convert.ToInt32(zipCodeTextBox.Text);
                user.User_Name = nameTextBox.Text;
                user.User_Birthdate = birthdateDatePicker.Date;
                user.User_Email = emailTextBox.Text;
                user.User_Phone = phoneTextBox.Text;
                user.User_Password = passwordPassBox.Password;

                // Serialize user object
                string jsonContents = JsonConvert.SerializeObject(user);

                // Http post request to web api. 
                var response = await httpClient.PostAsync("api/User", new StringContent(jsonContents.ToString(), Encoding.UTF8, "application/json"));

                // Message dialog.
                if (response.IsSuccessStatusCode)
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog("Tillykke, din bruger er nu oprettet");
                    messageDialog.Commands.Add(new UICommand("Okay"));
                    messageDialog.DefaultCommandIndex = 0;
                    await messageDialog.ShowAsync();

                    Frame.Navigate(typeof(Login), user);
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog("Error: Couldn't create user. Please try again later.");
                    messageDialog.Commands.Add(new UICommand("Okay"));
                    messageDialog.DefaultCommandIndex = 0;
                    await messageDialog.ShowAsync();
                }
            }
            
            // call method here to web api!
            //var response = await httpClient.GetAsync("api/Event");
            
        }


        private void cancel_Click(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Login));
        }



        // Not finally implemented
        private async Task<bool> isEmailAvailable(User user)
        {
            string uMail = user.User_Email;
            bool isAvailble = false;

            var response = await httpClient.GetAsync("api/User/" + uMail);

            //var response = await httpClient.GetAsync("api/Event");
            //if (response.IsSuccessStatusCode)
            //{
            //    var nEvent = await response.Content.ReadAsStringAsync();
            //    var eve = JsonArray.Parse(nEvent);

            //    foreach (var item in eve)


            return isAvailble;
        }
    }
}
